package com.cicc.beergamevirtualsimulationsystem.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cicc.beergamevirtualsimulationsystem.common.enums.roomEnum.Status;
import com.cicc.beergamevirtualsimulationsystem.entity.RoomEntity;
import com.cicc.beergamevirtualsimulationsystem.entity.RoomInfoManager;
import com.cicc.beergamevirtualsimulationsystem.service.RoomService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 房间相关定时任务
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class RoomTask {

    private final RoomService roomService;

    /**
     * 销毁长时间未开始的房间 每2小时执行一次
     */
    @Scheduled(cron = "0 0 0/2 * * ? ")
    private void destroyRoom() {
        log.info("开始执行销毁长时间存在的房间任务");
        // 要删除的房间的id集合
        List<RoomEntity> list = roomService.list(new LambdaQueryWrapper<RoomEntity>().in(RoomEntity::getStatus, Status.NOT_START.getCode(), Status.STARTED.getCode()));
        List<String> idList = list.stream().filter(room -> Objects.nonNull(room.getCreateTime())).filter(room -> {
            // 获取当前时间戳 判断房间的创建时间是否大于2小时
            return System.currentTimeMillis() - Long.parseLong(room.getCreateTime()) > 2 * 60 * 60 * 1000;
        }).map(RoomEntity::getId).toList();
        if (!idList.isEmpty()) {
            roomService.closeRoom(idList);
            // 清楚WS中相关房间的信息
            idList.forEach(roomId -> {
                log.info("清除WS中房间的信息:{}", roomId);
                RoomInfoManager.clearRoom(roomId,0);
            });
        }
    }


}
